package logrushook

import (
	"database/sql"
	"jgt-wallet/src/logger"
	"jgt-wallet/src/schema"
	"jgt-wallet/src/util"

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

// NewMySQLHook 创建mysql钩子
func NewMySQLHook(db *sql.DB) *MySQLHook {
	return &MySQLHook{db}
}

// MySQLHook mysql日志钩子
type MySQLHook struct {
	db *sql.DB
}

// Exec 写入日志到mysql
func (a *MySQLHook) Exec(entry *logrus.Entry) error {
	item := &schema.LogManage{
		RecordID: util.UUID(),
		Level:    entry.Level.String(),
		Message:  entry.Message,
		Created:  entry.Time.Unix(),
	}

	if data := entry.Data; data != nil && len(data) > 0 {
		if v, ok := data[logger.TypeField]; ok && v != nil {
			item.Type = v.(string)
			delete(data, logger.TypeField)
		}

		if v, ok := data[logger.UserIDField]; ok && v != nil {
			item.Creator = v.(string)
			delete(data, logger.UserIDField)
		}
		item.Data = util.JSONMarshalToString(data)
	}

	_, err := a.db.Exec("insert into s_log(`record_id`,`level`,`message`,`data`,`type`,`created`,`creator`) values(?,?,?,?,?,?,?);",
		item.RecordID, item.Level, item.Message, item.Data, item.Type, item.Created, item.Creator)
	if err != nil {
		return errors.Wrapf(err, "写入数据发生错误")
	}
	return nil
}
